<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="600px"
    :close-on-click-modal="false"
  >
    <div v-if="transition" class="transition-dialog">
      <!-- 流转信息 -->
      <div class="transition-info">
        <div class="info-row">
          <span class="label">当前状态：</span>
          <el-tag :type="getStatusType(transition.from_status)">
            {{ getStatusName(transition.from_status) }}
          </el-tag>
        </div>
        <div class="info-row">
          <span class="label">目标状态：</span>
          <el-tag :type="getStatusType(transition.to_status)">
            {{ getStatusName(transition.to_status) }}
          </el-tag>
        </div>
        <div v-if="transition.require_approval" class="info-row">
          <el-alert
            type="warning"
            :closable="false"
            show-icon
          >
            <template #title>
              <span>此状态流转需要审批</span>
            </template>
          </el-alert>
        </div>
      </div>

      <!-- 完成度信息 -->
      <div v-if="completionData" class="completion-info">
        <div class="info-title">当前完成度</div>
        <div class="completion-item">
          <span>综合完成度：</span>
          <template v-if="hasOverallCompletionPercent">
            <el-progress 
              :percentage="overallCompletionPercent"
              :status="getCompletionStatus(overallCompletionRatio ?? 0)"
            />
            <span class="percent-text">{{ overallCompletionPercent }}%</span>
          </template>
          <span v-else class="percent-text">--</span>
        </div>
      </div>

      <!-- 流转原因 -->
      <div class="reason-section">
        <el-form :model="form" label-width="100px">
          <el-form-item 
            label="流转原因" 
            :required="transition.require_reason"
          >
            <el-input
              v-model="form.reason"
              type="textarea"
              :rows="4"
              placeholder="请输入流转原因"
              maxlength="500"
              show-word-limit
            />
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleConfirm"
          :loading="submitting"
          :disabled="transition?.require_reason && !form.reason"
        >
          确认流转
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import versionAPI from '@/api/version'
import type {
  VersionTransitionRule,
  VersionCompletion
} from '@/types/version'
import { BusinessError } from '@/types/api'
import { useVersionStates } from '@/composables/useVersionStates'

interface Props {
  modelValue: boolean
  versionId: string
  transition: VersionTransitionRule | null
  completionData?: VersionCompletion | null
}

const props = defineProps<Props>()
const { getStateByCode } = useVersionStates()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  success: []
}>()

const form = ref({
  reason: ''
})

const submitting = ref(false)

const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const dialogTitle = computed(() => {
  if (props.transition) {
    return `状态流转 - ${props.transition.name}`
  }
  return '状态流转'
})

// 监听对话框打开，重置表单
watch(() => props.modelValue, (visible) => {
  if (visible) {
    form.value.reason = ''
  }
})

// 处理确认
const handleConfirm = async () => {
  if (!props.transition) return

  if (props.transition.require_reason && !form.value.reason) {
    ElMessage.warning('请填写流转原因')
    return
  }

  try {
    submitting.value = true

    // 流转前验证条件是否满足
    try {
      const readiness = await versionAPI.getTransitionReadiness(
        props.versionId,
        props.transition.to_status
      )
      const targetReadiness = readiness?.readiness?.find(
        item => item.target_status === props.transition?.to_status
      )
      if (targetReadiness && !targetReadiness.is_ready) {
        const unmetList = Array.isArray(targetReadiness.unmet_conditions)
          ? targetReadiness.unmet_conditions
          : []
        if (unmetList.length > 0) {
          await ElMessageBox.alert(
            `<div style="text-align:left;">${unmetList.map(item => `<div>${item}</div>`).join('')}</div>`,
            '状态流转条件未满足',
            {
              type: 'warning',
              dangerouslyUseHTMLString: true
            }
          )
        } else {
          ElMessage.warning('状态流转条件未满足，请检查版本状态。')
        }
        return
      }
    } catch (readinessError) {
      console.warn('获取流转准备情况失败:', readinessError)
      // 如果前置校验失败，继续交由后端校验
    }

    // 如果需要审批，提交审批申请
    if (props.transition.require_approval) {
      await versionAPI.submitTransitionApproval(props.versionId, {
        to_status: props.transition.to_status,
        reason: form.value.reason,
        approval_flow_type: 'simple'
      })
      ElMessage.success('审批申请已提交，等待审批')
    } else {
      // 直接流转
      await versionAPI.transitionStatus(props.versionId, {
        new_status: props.transition.to_status,
        reason: form.value.reason,
        comment: form.value.reason
      })
      ElMessage.success('状态流转成功')
    }

    dialogVisible.value = false
    emit('success')
  } catch (error: any) {
    console.error('状态流转失败:', error)

    const displayError = (errMessage: string, details?: string[]) => {
      if (details && details.length > 0) {
        ElMessageBox.alert(
          `<div style="text-align:left;">${details.map(item => `<div>${item}</div>`).join('')}</div>`,
          errMessage,
          {
            type: 'warning',
            dangerouslyUseHTMLString: true
          }
        )
      } else {
        ElMessage.error(errMessage)
      }
    }

    if (error instanceof BusinessError) {
      const unmet = Array.isArray(error.details?.unmet_conditions)
        ? error.details?.unmet_conditions as string[]
        : undefined
      displayError(error.message || '状态流转失败', unmet)
    } else if (error?.message) {
      displayError(error.message)
    } else {
      displayError('状态流转失败')
    }
  } finally {
    submitting.value = false
  }
}

const getStatusType = (status: string) => {
  // 优先使用状态管理中的颜色
  const state = getStateByCode(status)
  if (state?.color) {
    const colorMap: Record<string, 'success' | 'info' | 'warning' | 'danger' | 'primary'> = {
      '#67C23A': 'success',
      '#52c41a': 'success',
      '#F56C6C': 'danger',
      '#ff4d4f': 'danger',
      '#E6A23C': 'warning',
      '#faad14': 'warning',
      '#409EFF': 'primary',
      '#1890ff': 'primary',
      '#909399': 'info',
      '#8c8c8c': 'info',
      '#d9d9d9': 'info'
    }
    if (colorMap[state.color]) {
      return colorMap[state.color]
    }
  }
  
  // 后备映射
  const typeMap: Record<string, 'success' | 'info' | 'warning' | 'danger' | 'primary'> = {
    draft: 'info',
    planning: 'primary',
    development: 'primary',
    testing: 'warning',
    pre_release: 'warning',
    released: 'success',
    deprecated: 'danger',
    archived: 'info'
  }
  return typeMap[status] || 'info'
}

const getStatusName = (status: string) => {
  // 优先使用状态管理中的名称
  const state = getStateByCode(status)
  if (state?.name) {
    return state.name
  }
  
  // 后备映射
  const nameMap: Record<string, string> = {
    draft: '草稿',
    planning: '规划中',
    development: '开发中',
    testing: '测试中',
    pre_release: '预发布',
    released: '已发布',
    deprecated: '已废弃',
    archived: '已归档'
  }
  return nameMap[status] || status
}

const getCompletionStatus = (completion: number) => {
  if (completion >= 0.98) return 'success'
  if (completion >= 0.75) return ''
  return 'exception'
}

// 兼容多种后端字段，计算综合完成度
const overallCompletionRatio = computed(() => {
  const data = props.completionData as Record<string, any> | null | undefined
  if (!data) return null

  const candidates: Array<number | undefined> = [
    data.overall_completion,
    data.overallCompletion,
    data.overall_progress,
    data.overallProgress,
    data.overall_completion_rate,
    data.overallCompletionRate,
    data.overall_completion_percent ? data.overall_completion_percent / 100 : undefined,
    data.overallCompletionPercent ? data.overallCompletionPercent / 100 : undefined
  ]

  const value = candidates.find(v => typeof v === 'number' && !Number.isNaN(v))
  if (value === undefined) return null

  // 如果后端直接给百分数，转换为 0-1
  const ratio = value > 1 ? value / 100 : value
  return Math.min(Math.max(ratio, 0), 1)
})

const overallCompletionPercentRaw = computed(() => {
  if (overallCompletionRatio.value === null) return null
  return Math.round(overallCompletionRatio.value * 100)
})

const hasOverallCompletionPercent = computed(() => overallCompletionPercentRaw.value !== null)

const overallCompletionPercent = computed(() => overallCompletionPercentRaw.value ?? 0)
</script>

<style scoped lang="scss">
.transition-dialog {
  .transition-info {
    margin-bottom: 20px;

    .info-row {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      .label {
        width: 100px;
        color: #606266;
      }
    }
  }

  .completion-info {
    margin-bottom: 20px;
    padding: 16px;
    background: #f5f7fa;
    border-radius: 4px;

    .info-title {
      font-size: 14px;
      font-weight: 600;
      margin-bottom: 12px;
    }

    .completion-item {
      display: flex;
      align-items: center;
      gap: 12px;

      span {
        width: 100px;
        font-size: 14px;
      }

      .percent-text {
        width: auto;
        min-width: 48px;
        color: #606266;
        text-align: right;
      }
    }
  }

  .reason-section {
    margin-bottom: 20px;
  }
}
</style>

